import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Modal, Switch } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import UserForm from '../../../comopnents/user-manage/UserForm';
import Item from 'antd/lib/list/Item';
const { confirm } = Modal
// const { Option } = Select;

export default function UserList() {
    const [dataSource, setDataSource] = useState([]);
    const [addVisible, setAddVisible] = useState(false)
    const [updateVisible, setUpdateVisible] = useState(false)
    const [roleList, setRoleList] = useState([])
    const [regionList, setRegionList] = useState([])
    const [current, setCurrent] = useState(null)
    const [isUpdateDisable, setIsUpdateDisable] = useState(false)
    const addForm = useRef(null)
    const updateForm = useRef(null)

    const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))
    const roleObj = {
        "1": "superadmin",
        "2": "admin",
        "3": "editor"
    }
    useEffect(() => {
        axios.get("/users?_expand=role").then(res => {
            const list = res.data
            // 登录对应用户只能看到自己所在区域的信息
            setDataSource(roleObj[roleId] === "superadmin" ? list : [
                ...list.filter(Item => Item.username === username),
                ...list.filter(Item => Item.region === region && roleObj
                [Item.reloId] === "editor")
            ])
            // console.log(res.data)
        })
    }, [roleId, region, username, roleObj])

    useEffect(() => {
        axios.get("/regions").then(res => {
            const list = res.data
            setRegionList(list)
            // console.log(res.data)
        })
    }, [])
    useEffect(() => {
        axios.get("/roles").then(res => {
            const list = res.data
            setRoleList(list)
            // console.log(res.data)
            console.log(list);
        })
    }, [])
    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            key: 'name',  // 可写可不写
            // table表格中有筛选和排序的功能，这里是对其进行解构遍历渲染
            filters: [
                ...regionList.map(Item => ({
                    text: Item.title,
                    value: Item.value
                })),
                {
                    text: "全球",
                    value: "全球",
                }
            ],
            onFilter: (value, item) => {
                if (value === "全球") {
                    return item.region === ""
                }
                return item.region === value
            },
            render: (region) => <b>{region === '' ? '全球' : region}</b>
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: (role) => {
                return role?.roleName
            }
        },
        {
            title: '用户名',
            dataIndex: 'username',
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, Item) => <div>
                <Switch checked={roleState} disabled={Item.default} onChange={() => { handleChange(Item) }}></Switch>
            </div>
        },
        {
            title: '操作',
            render: (Item) => <div>
                <Button shape="circle" danger>
                    <DeleteOutlined onClick={() => confirmMethod(Item)} />
                </Button>
                <div style={{ display: "inline-block", padding: "4px" }}></div>
                <Button shape="circle" type="primary" primary><EditOutlined disabled={Item.default} onClick={(Item) =>
                    handleUpdate(Item)
                } /></Button>
            </div>
        },
    ];


    // 删除弹窗
    const confirmMethod = (Item) => {
        confirm({
            title: '你确定要删除吗？',
            icon: <ExclamationCircleOutlined />,

            onOk() {
                deleteMethod(Item)
            },
            onCancel() {
            },
        });
    }

    // 删除操作
    const deleteMethod = (Item) => {
        // console.log(Item);
        setDataSource(dataSource.filter(data => data.id !== Item.id))
        axios.delete(`/users/${Item.id}`)
    }

    ////添加用户操作
    // 取消按钮
    const onCancel = () => {
        setAddVisible(false)
    }

    const addFormOk = () => {
        // console.log(addForm);
        // forwardRef高阶Ref组件下.current.validateFields() 后面去返回结果可以拿到From表单的值
        addForm.current.validateFields().then(value => {
            // console.log(value);
            setAddVisible(false)
            addForm.current.resetFields()
            // 添加到后端的数据要生成一个Id，在设置DataSource方面后面删除和更新
            axios.post(`/users`, {
                ...value,
                "roleState": true,
                "default": false,
            }).then(res => {
                // console.log(res.data);
                setDataSource([...dataSource, {
                    ...res.data,
                    role: roleList.filter(Item => Item.id === value.roleId)[0]
                }])
            })
        }).catch(err => {
            // console.log(err);
        })
    }

    //switch状开关处理
    const handleChange = (Item) => {
        // console.log(Item);
        Item.roleState = !Item.roleState
        setDataSource([...dataSource])
        axios.patch(`/users/${Item.id}`, {
            roleState: Item.roleState
        })
    };

    //// 修改更新操作
    const handleUpdate = (Item) => {
        setTimeout(() => {
            setUpdateVisible(true)
            if (Item.roleId === 1) {
                // 禁用
                setIsUpdateDisable(true)
            } else {
                // 取消禁用
                setIsUpdateDisable(false)
            }
            updateForm.current.setFieldsValue(Item)
        }, 0)
        setCurrent(Item)
    }

    // 取消按钮
    // const onCancel = () => {
    //     setUpdateVisible(false)
    // }

    // 修改更新确定按钮
    const updateFormOk = () => {
        updateForm.current.validateFields().then(value => {
            console.log(value);
            setUpdateVisible(false)
            setDataSource(dataSource.map(Item => {
                if (Item.id === current.id) {
                    return {
                        ...Item,
                        ...value,
                        role: roleList.filter(data => data.id === value.roleId)[0]
                    }
                }
                return Item
            }))
            setIsUpdateDisable(!isUpdateDisable)
            axios.patch(`/users/${current.id}`)
        })
    }

    return (
        <div>
            <Button type="primary" onClick={() => {
                setAddVisible(true)
            }}>添加用户</Button>
            <Table
                columns={columns}
                dataSource={dataSource}
                pagination={{
                    pageSize: 5
                }}
                rowKey={Item => Item.id}
            />
            <Modal
                visible={addVisible}
                title="添加用户信息"
                okText="确定"
                cancelText="取消"
                onCancel={onCancel}
                onOk={() => addFormOk()}
            >
                <UserForm ref={addForm} regionList={regionList} roleList={roleList}></UserForm>
            </Modal>
            <Modal
                visible={updateVisible}
                title="更新用户信息"
                okText="更新"
                cancelText="取消"
                onCancel={() => {
                    setUpdateVisible(false)
                    setIsUpdateDisable(!isUpdateDisable)
                }}
                onOk={() => updateFormOk()}
            >
                <UserForm ref={updateForm} regionList={regionList} roleList={roleList} isUpdateDisable={isUpdateDisable} isUpdte={true}></UserForm>
            </Modal>
        </div >
    )
}
